let Consts = {
    OpenDataKeys: {
        InitKey: "initKey",
        ScoreKey: "MaxScore",
        FishCountKey: "fishCount",
        DepthKey: "waterDepth", // json.string
    },
    DomainAction: {
        FetchFriend: "FetchFriend",
        FetchGroup: "FetchGroup",
        FetchFriendScore: "FetchFriendScore", //好友捕鱼数量排行
        FetchFriendPassScore: "FetchFriendPassScore", //好友打卡
        FetchFriendDepth: "FetchFriendDepth", //好友水深排行
        HorConmpar: "HorConmpar", //横向比较 horizontal comparison
        MoreFriend: "MoreFriend", //超越好友
        Paging: "Paging",
        Scrolling: "Scrolling",
    },
}

const PAGE_SIZE = 10;
const ITEM_WIDTH = 604;
const ITEM_HEIGHT = 79;
const MASK_OFFSETY = 450
const SELF_OFFSETY = 500
let Max_Page = 0;
const RANK_PAGE_HEIGHT = ITEM_HEIGHT * PAGE_SIZE;

const dataSorter = (gameDatas, field = Consts.OpenDataKeys.ScoreKey) => {
    let data = []
    for (let i = 0; i < gameDatas.length; i++) {
        if (gameDatas[i].KVDataList[0]) {
            //for(var j=0;j<15;j++){
            data.push(gameDatas[i])
            //}
        }
    }

    let newData = data.sort((a, b) => {
        let va = a.KVDataList[0] ? a.KVDataList[0].value - 0 : 0
        let vb = b.KVDataList[0] ? b.KVDataList[0].value - 0 : 0
        return vb - va;
    });
    Max_Page = Math.ceil(data.length / PAGE_SIZE) - 1
    return newData
}

class RankListRenderer {
    constructor() {
        this.clearFlag = false
        this.offsetY = 0;
        this.maxOffsetY = 0;
        this.gameDatas = []; //https://developers.weixin.qq.com/minigame/dev/document/open-api/data/UserGameData.html
        // this.gameLevelDatas = [];
        this.curDataType = Consts.OpenDataKeys.ScoreKey
        this.curPageIndex = 0; //当前页码
        this.drawIconCount = 0;
        this.rankCanvasList = [];

        this.selfUserInfo = null //avatarUrl //https://developers.weixin.qq.com/minigame/dev/document/open-api/data/wx.getUserInfo.html
        this.selfData = null; //当前用户的排行数据
        this.cur_index = -1;
        this.init();
    }

    init() {
        this.sharedCanvas = wx.getSharedCanvas();
        this.sharedCtx = this.sharedCanvas.getContext('2d');


        //背景1
        this.itemBg = wx.createImage();
        this.itemBg.src = `wx_scope/sub_ui/item-bg.png`;
        this.scoreBg = wx.createImage();
        this.scoreBg.src = `wx_scope/sub_ui/score-bg.png`;
        this.headFrame = wx.createImage();
        this.headFrame.src = `wx_scope/item_ui/framebg.png`;
        this.line = wx.createImage();
        this.line.src = `wx_scope/sub_ui/line.png`;
        this.rank1 = wx.createImage();
        this.rank1.src = `wx_scope/item_ui/rankbg_1.png`;
        this.rank2 = wx.createImage();
        this.rank2.src = `wx_scope/item_ui/rankbg_1.png`;
        this.rank3 = wx.createImage();
        this.rank3.src = `wx_scope/item_ui/rankbg_1.png`;
        this.rank4 = wx.createImage();
        this.rank4.src = `wx_scope/item_ui/rankbg_1.png`;
        this.labelbg = wx.createImage();
        this.labelbg.src = `wx_scope/item_ui/labelbg.png`;
        this.coinImg = wx.createImage();
        this.coinImg.src = `wx_scope/sub_ui/coin.png`;
        this.rankCount1 = wx.createImage();
        this.rankCount1.src = `wx_scope/sub_ui/01.png`;
        this.rankCount2 = wx.createImage();
        this.rankCount2.src = `wx_scope/sub_ui/02.png`;
        this.rankCount3 = wx.createImage();
        this.rankCount3.src = `wx_scope/sub_ui/03.png`;
        this.norankCount = wx.createImage();
        this.norankCount.src = `wx_scope/sub_ui/wumingci.png`;

        this.fetchSelfInfo(); //获取当前用户的信息
        this.getSelfData(); //获取当前用户的分数，如果没有就设置为0
        this.icon_arr = [];
        this.icon_url = [];
        this.cache_friend_icon();

        this.rank = 0;
    }


    listen() {
        console.log ("开始监听")
        wx.onMessage(msg => {
            console.log ("收到消息 = " + msg.action)
            switch (msg.action) {
                case Consts.DomainAction.HorConmpar: //横向排行
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    this.clearFlag = true
                    this.fetchHorFriendScoreData(msg.data)
                    break;
                case Consts.DomainAction.FetchFriendScore: //分数排行
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    this.curPageIndex = 0;
                    this.clearFlag = true
                    this.FetchFriendScoreData([Consts.OpenDataKeys.ScoreKey]);

                    break;
                case Consts.DomainAction.FetchFriendPassScore: //打卡排行
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    this.curPageIndex = 0;
                    this.clearFlag = true
                    this.FetchFriendScoreData([Consts.OpenDataKeys.FishCountKey]);
                    break;

                case Consts.DomainAction.MoreFriend: //超越好友
                    //console.log("y="+msg.dataEx);
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    // if (!msg.data) {
                    //     return;
                    // }
                    //this.clearFlag = true
                    this.MoreFriendData(msg.data);
                    break;

                case Consts.DomainAction.Paging: //分页监听
                    const page = msg.data;
                    this.curPageIndex += page
                    if (this.curPageIndex < 0) {
                        this.curPageIndex = 0;
                        return;
                    } else if (this.curPageIndex > Max_Page) {
                        this.curPageIndex = Max_Page
                        return;
                    }
                    this.showPagedRanks(this.curPageIndex);
                    break;
                case 'SelfIcon': //玩家头像
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    this.SelfIcon(msg.data, msg.dataEx);
                    break;
                case 'PlayerIcon': //个人头像
                    this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height);
                    this.PlayerIcon(msg.data, msg.dataEx);
                    break;
                case Consts.DomainAction.Scrolling:
                    this.clearFlag = false
                    if (!this.gameDatas.length) {
                        return;
                    }
                    const deltaY = msg.data;
                    // console.log('deltaY', deltaY)
                    const newOffsetY = this.offsetY + deltaY;
                    // console.log('newOffsetY', deltaY)
                    if (newOffsetY < 0) {
                        // console.log("前面没有更多了");
                        return;
                    }
                    if (newOffsetY + PAGE_SIZE * ITEM_HEIGHT > this.maxOffsetY) {
                        // console.log("后面没有更多了");
                        return;
                    }
                    this.offsetY = newOffsetY;
                    this.showRanks(newOffsetY);
                    break;
                default:
                    break;
            }
        });
    }

    //缓存好友头像
    cache_friend_icon() {
        wx.getFriendCloudStorage({
            keyList: [
                Consts.OpenDataKeys.ScoreKey,
            ],
            success: res => {
                this.gameDatas = dataSorter(res.data, this.curDataType);
                for (var i = 0; i < this.gameDatas.length; i++) {
                    var avatarUrl = this.gameDatas[i].avatarUrl;
                    const avatarImg = wx.createImage();
                    avatarImg.src = avatarUrl;
                    this.icon_arr.push(avatarImg);
                    this.icon_url.push(avatarUrl.trim());
                    //avatarImg.onload = () => {

                    //};
                }
            },
            fail: res => { },
        });

    }

    fetchSelfInfo() {
        wx.getUserInfo({
            openIdList: ["selfOpenId"],
            success: res => {
                this.selfUserInfo = res.data[0];
            }
        })
    }

    getSelfData() {
        wx.getUserCloudStorage({
            keyList: [Consts.OpenDataKeys.ScoreKey],
            success: res => {
                if (!res.KVDataList[0]) {
                    wx.setUserCloudStorage({
                        KVDataList: [{
                            key: Consts.OpenDataKeys.ScoreKey,
                            value: "0"
                        }],
                        success: res => {

                        },
                        fail: res => {
                            console.log('reserr', res)
                        },
                    })
                }
            },
            fail: res => { },
        })
    }



    //取出所有好友数据按分数排名
    FetchFriendScoreData(key) {
        //请求最新排行榜数据
        wx.getFriendCloudStorage({
            keyList: key,
            success: res => {
                this.curDataType = Consts.OpenDataKeys.ScoreKey
                this.gameDatas = dataSorter(res.data, this.curDataType);

                const dataLen = this.gameDatas.length;
                this.offsetY = 0;
                this.maxOffsetY = dataLen * ITEM_HEIGHT + 50;
                if (dataLen) {
                    this.showPagedRanks(0);
                }
                let rank = 0;
                for (let i = 0; i < this.gameDatas.length; i++) {
                    if (this.gameDatas[i].avatarUrl === this.selfUserInfo.avatarUrl) {
                        this.selfData = this.gameDatas[i];
                        this.rank = i + 1;
                        break;
                    }
                }
                setTimeout(() => {
                    this.sharedCtx.clearRect(0, MASK_OFFSETY, this.sharedCanvas.width, 400);
                    this.drawRankItemEx(this.sharedCtx, this.rank, this.selfData, SELF_OFFSETY, true);
                }, 2)
            },
            fail: res => { },
        });

    }


    // 横向比较关卡得分
    fetchHorFriendScoreData() {
        wx.getFriendCloudStorage({
            keyList: [
                Consts.OpenDataKeys.ScoreKey,
            ],
            success: res => {
                this.curDataType = Consts.OpenDataKeys.ScoreKey
                this.gameDatas = dataSorter(res.data, this.curDataType);
                this.horizontalgetSelf()
            },
            fail: res => { },
        });
    }

    //超越好友比较
    MoreFriendData(score) {
        //if(this.gameDatas.length > 0){//不请求排行榜数据
        //    this.moreThenFriend(score);
        //}else{
        //请求最新排行榜数据
        wx.getFriendCloudStorage({
            keyList: [
                Consts.OpenDataKeys.ScoreKey,
            ],
            success: res => {
                this.curDataType = Consts.OpenDataKeys.ScoreKey
                this.gameDatas = dataSorter(res.data, this.curDataType);
                this.moreThenFriend(score);
            },
            fail: res => { },
        });
        //}
    }

    /**玩家头像*/
    SelfIcon(data, y) {
        wx.getUserInfo({
            openIdList: ["selfOpenId"],
            success: res => {
                this.selfUserInfo = res.data[0];
                data = this.selfUserInfo;
                let ctx = this.sharedCtx;
                const sharedWidth = this.sharedCanvas.width;
                const sharedHeight = this.sharedCanvas.height;
                //背景
                //ctx.drawImage(this.bgImg,  0,0, 140, 160);
                //头像
                const avatarX = 50;
                const avatarY = -120 - Math.round(y);
                const avatarW = 60;
                const avatarH = 60;
                this.drawAvatar(ctx, data.avatarUrl, avatarX, avatarY, avatarW, avatarH, (avatarImg) => {
                    ctx.drawImage(avatarImg, avatarX, avatarY, avatarW, avatarH);

                })
                ctx.textAlign = "center";
                ctx.baseLine = "middle";
                ctx.fillStyle = "#ffffff";
                ctx.font = "bold 26px Helvetica";
                ctx.fillText(data.nickName, 170, avatarY + 55);
            }
        })
    }


    /**个人头像*/
    PlayerIcon(data, y) {
        console.log(data)
        wx.getUserInfo({
            openIdList: ["selfOpenId"],
            success: res => {
                this.selfUserInfo = res.data[0];
                data = this.selfUserInfo;
                let ctx = this.sharedCtx;
                const sharedWidth = this.sharedCanvas.width;
                const sharedHeight = this.sharedCanvas.height;
                //背景
                //ctx.drawImage(this.bgImg,  0,0, 140, 160);
                //头像
                let avatarX = this.sharedCanvas.width * 0.06;
                let avatarY = 100;
                let radius = 30;
                let dy = 0;
                this.drawAvatar(ctx, data.avatarUrl, avatarX, avatarY, radius * 2, radius * 2, (avatarImg) => {
                    //ctx.drawImage(avatarImg, avatarX - 35, avatarY + itemY, avatarW, avatarH);
                    ctx.save() //保存上下文
                    ctx.beginPath(); //开始创建路径
                    ctx.arc(avatarX, 50 + dy + avatarY, radius + 5, 0, 2 * Math.PI, false); //创建圆形路径
                    ctx.closePath(); //关闭路径
                    ctx.fillStyle = 'Rgba(255,255,255,1)'; //设置颜色
                    ctx.fill(); //填充图形
                    ctx.beginPath() //开始绘制
                    ctx.arc(avatarX, 50 + dy + avatarY, radius, 0, 2 * Math.PI, false) //画一个圆    
                    ctx.clip() //裁剪这个圆
                    ctx.drawImage(avatarImg, avatarX - radius, avatarY + dy + 20, radius * 2, radius * 2) //将图片绘制进圆
                    ctx.restore() //恢复上下文  接下来可以进行其他绘制操作                

                })
            }
        })
    }



    // 根据滑动偏移绘制排行榜画布
    showRanks(offsetY) {
        this.curOffsetY = offsetY
        const sharedWidth = this.sharedCanvas.width;
        const sharedHeight = this.sharedCanvas.height;
        this.sharedCtx.clearRect(0, 0, sharedWidth, sharedHeight);
        if (this.clearFlag) {
            this.clearFlag = false
            this.rankCanvasList = [];
        }

        const pageY = offsetY % RANK_PAGE_HEIGHT;
        const pageIndex = Math.floor(offsetY / RANK_PAGE_HEIGHT);
        const isOverOnePage = pageY + sharedHeight > RANK_PAGE_HEIGHT;

        let rankCanvas = this.getCanvasByPageIndex(pageIndex);
        if (!isOverOnePage) {
            this.sharedCtx.drawImage(rankCanvas, 0, pageY, sharedWidth, sharedHeight, 0, 0, sharedWidth, sharedHeight);
        } else {
            //绘制当前页后半部分
            const partialHeight = RANK_PAGE_HEIGHT - pageY;
            this.sharedCtx.drawImage(rankCanvas, 0, pageY, sharedWidth, partialHeight, 0, 0, sharedWidth, partialHeight);

            //绘制下一页前半部分
            rankCanvas = this.getCanvasByPageIndex(pageIndex + 1);
            this.sharedCtx.drawImage(rankCanvas, 0, 0, sharedWidth, sharedHeight - partialHeight, 0, partialHeight, sharedWidth, sharedHeight - partialHeight);
        }
        this.sharedCtx.clearRect(0, MASK_OFFSETY, this.sharedCanvas.width, 400);
        this.drawRankItemEx(this.sharedCtx, this.rank, this.selfData, SELF_OFFSETY, true);
    }
    // 获取指定页码的排行榜
    getCanvasByPageIndex(pageIndex) {
        let canvas = this.rankCanvasList[pageIndex];
        if (!canvas) {
            canvas = wx.createCanvas();
            canvas.width = this.sharedCanvas.width;
            canvas.height = RANK_PAGE_HEIGHT;
            this.rankCanvasList[pageIndex] = canvas;
            const ctx = canvas.getContext('2d');
            this.drawPagedRanks(ctx, pageIndex);
        }
        return canvas;
    }
    drawPagedRanks(ctx, pageIndex) {
        for (let i = 0; i < PAGE_SIZE; i++) {
            const pageOffset = pageIndex * PAGE_SIZE;
            const data = this.gameDatas[pageOffset + i];
            if (!data) continue;
            this.drawRankItemEx(ctx, pageOffset + i + 1, data, ITEM_HEIGHT * i)
        }
    }

    drawAvatar(ctx, avatarUrl, x, y, w, h, cb) {
        var index = this.icon_url.indexOf(avatarUrl.trim());
        if (index > -1) {
            var icon_img = this.icon_arr[index];
            cb(icon_img);
            return;
        }


        const avatarImg = wx.createImage();
        avatarImg.src = avatarUrl;
        avatarImg.onload = () => {
            cb(avatarImg);
        };


    }

    showPagedRanks(page) {
        const pageStart = page * PAGE_SIZE;
        if (pageStart > this.gameDatas.length || pageStart < 0) {
            return
        }
        const pagedData = this.gameDatas.slice(pageStart, pageStart + PAGE_SIZE);
        const pageLen = pagedData.length;
        this.sharedCtx.clearRect(0, 0, this.sharedCanvas.width, this.sharedCanvas.height - 180);
        for (let i = 0, len = pageLen; i < len; i++) {
            this.drawRankItemPage(this.sharedCtx, i, pageStart + i + 1, pagedData[i]);
        }
    }

    // 翻页时绘制
    drawRankItemPage(ctx, index, rank, data) {
        const itemGapY = (ITEM_HEIGHT + 5) * index;
        this.drawRankItemEx(ctx, rank, data, itemGapY)
    }


    drawRankItemEx(ctx, rank, data, itemGapY, self = false) {
        const itemGapX = 0;
        const nick = data.nickname.length <= 6 ? data.nickname : data.nickname.substr(0, 5) + "...";
        const kvData = data.KVDataList[0];
        const grade = kvData ? kvData.value : 0;

        //背景
        switch (rank) {
            case 1:
                ctx.drawImage(this.rank1, itemGapX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
                ctx.drawImage(this.rankCount1, itemGapX + 10, itemGapY + 7, 114, 71);
                break;
            case 2:
                ctx.drawImage(this.rank2, itemGapX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
                ctx.drawImage(this.rankCount2, itemGapX + 10, itemGapY + 7, 115, 71);
                break;
            case 3:
                ctx.drawImage(this.rank3, itemGapX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
                ctx.drawImage(this.rankCount3, itemGapX + 10, itemGapY + 7, 120, 70);
                break;
            default:
                ctx.drawImage(this.rank4, itemGapX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
                ctx.drawImage(this.norankCount, itemGapX + 10, itemGapY + 7, 100, 94);
                break;
        }

        if (rank < 5) {
            //ctx.drawImage(this.labelbg, itemGapX + 10, itemGapY + 15, 90, 42);
        }

        ctx.drawImage(this.headFrame, 156, itemGapY + 15.5, 52, 56);

        //名次 这里可以设置前几名的名次背景
        {
            ctx.fillStyle = "#ffffff";
            ctx.textAlign = "center";
            ctx.baseLine = "middle";
            ctx.font = "bold 25px Helvetica";
            ctx.strokeText(`${rank}`, 70 + itemGapX, 50 + itemGapY);
            ctx.fillText(`${rank}`, 70 + itemGapX, 50 + itemGapY);    
        }

        //头像
        const avatarX = 183;
        const avatarY = itemGapY - 7;
        const avatarW = 30;
        const avatarH = 30;

        /** 绘制圆形头像 */
        let radius = 21;
        this.drawAvatar(ctx, data.avatarUrl, avatarX, avatarY, radius * 2, radius * 2, (avatarImg) => {
            //ctx.drawImage(avatarImg, avatarX - 35, avatarY + itemY, avatarW, avatarH);
            ctx.save() //保存上下文
            ctx.beginPath(); //开始创建路径
            ctx.arc(avatarX, 50 + avatarY, radius, 0, 2 * Math.PI, false); //创建圆形路径
            ctx.closePath(); //关闭路径
            ctx.fillStyle = 'Rgba(255,255,255,1)'; //设置颜色
            ctx.fill(); //填充图形
            ctx.beginPath() //开始绘制
            ctx.arc(avatarX, 50 + avatarY, radius, 0, 2 * Math.PI, false) //画一个圆    
            ctx.clip() //裁剪这个圆
            ctx.drawImage(avatarImg, avatarX - radius, avatarY + 31, radius * 2, radius * 2) //将图片绘制进圆
            ctx.restore() //恢复上下文  接下来可以进行其他绘制操作                

        })

        // 名字
        {
            ctx.fillStyle = "#ffffff";
            ctx.textAlign = "center";
            ctx.baseLine = "middle";
            ctx.font = "bold 30px Arial";
            // ctx.strokeText(nick, 270 + itemGapX, 50 + itemGapY);
            ctx.fillText(nick, 320 + itemGapX, 50 + itemGapY);
        }

        //分数
        {
            ctx.strokeStyle = "#000000";
            ctx.fillStyle = "#ffffff";
            ctx.textAlign = "right";
            ctx.baseLine = "middle";
            ctx.lineWidth = 4;
            ctx.font = "bold 35px Arial";

            const textWidth = ctx.measureText(`${grade}`).width;
            
            // ctx.strokeText(`${grade}`, 570, 50 + itemGapY);
            ctx.fillText(`${grade}`, 570, 50 + itemGapY);
        }
    }


    //横向排行item绘制
    drawRankItemHor(ctx, rank, data, itemPos, index) {
        if (!data) return;
        let width = this.sharedCanvas.width
        const nick = data.nickname.length <= 10 ? data.nickname : data.nickname.substr(0, 10) + "...";
        const kvData = data.KVDataList[0];
        const grade = kvData ? kvData.value : 0;

        let avatarX
        if (itemPos === 1) {
            avatarX = width / 3 - 30;
        } else if (itemPos === 2) {
            avatarX = width * 0.5;
        } else if (itemPos === 3) {
            avatarX = width * 2 / 3 + 30;
        }

        //名次
        /*
        if(rank == 1){
            ctx.fillStyle = "#FF0000";
        }else if (rank == 2 ) {
            ctx.fillStyle = "#FF69B4";
        }else if (rank == 3 ) {
            ctx.fillStyle = "#CD8500";
        }else{
            ctx.fillStyle = "#ffffff";
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "36px Helvetica";
        ctx.fillText(rank, avatarX, 65 + itemY);

        //名字
        ctx.fillStyle = "#ffffff";
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "22px Helvetica";
        ctx.fillText(nick, avatarX, 186 + itemY);
        */

        //分数
        ctx.fillStyle = "#000000";
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "24px Helvetica";
        ctx.fillText(`第${grade}关`, avatarX, 124);

        //头像
        let avatarY = 20;
        let radius = 30;
        let dy = 0;
        if (rank == 1) {
            radius = 40;
            avatarY = 10;
        }
        //const avatarH = 60;
        this.drawAvatar(ctx, data.avatarUrl, avatarX, avatarY, radius * 2, radius * 2, (avatarImg) => {
            //ctx.drawImage(avatarImg, avatarX - 35, avatarY + itemY, avatarW, avatarH);
            ctx.save() //保存上下文
            ctx.beginPath(); //开始创建路径
            ctx.arc(avatarX, 50 + dy, radius + 5, 0, 2 * Math.PI, false); //创建圆形路径
            ctx.closePath(); //关闭路径
            ctx.fillStyle = 'Rgba(255,255,255,1)'; //设置颜色
            ctx.fill(); //填充图形
            ctx.beginPath() //开始绘制
            ctx.arc(avatarX, 50 + dy, radius, 0, 2 * Math.PI, false) //画一个圆    
            ctx.clip() //裁剪这个圆
            ctx.drawImage(avatarImg, avatarX - radius, avatarY + dy, radius * 2, radius * 2) //将图片绘制进圆
            ctx.restore() //恢复上下文  接下来可以进行其他绘制操作                

        })

    }

    horizontalgetSelf() {
        console.log('horizontalgetSelf', this.gameDatas)
        let one = null;
        let two = null;
        let three = null;
        let oneNum = 0;
        let twoNum = 0;
        let threeNum = 0;
        let isone = false;
        this.gameDatas.map((obj, i) => {
            if (this.selfUserInfo.avatarUrl == obj.avatarUrl) {
                if (i == 0) {
                    isone = true;
                    one = obj;
                    two = this.gameDatas[i + 1];
                    three = this.gameDatas[i + 2];
                    oneNum = 1;
                    twoNum = 2;
                    threeNum = 3;
                } else {
                    isone = false;
                    one = this.gameDatas[i - 1];
                    two = obj;
                    oneNum = i;
                    twoNum = i + 1;
                    three = this.gameDatas[i + 1];
                    threeNum = i + 2;
                }
                this.horizontalComparison(one, two, three, oneNum, twoNum, threeNum, isone);
            }
        })

    }

    //横向关卡比较绘制
    horizontalComparison(one, two, three, oneNum, twoNum, threeNum, isone) {
        let ctx = this.sharedCtx; //175+40+35
        // ctx.drawImage(this.resultItemBg, 65, 250, 164, 268);

        //名次
        if (isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }

        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "bold 30px Helvetic";
        ctx.fillText(`${oneNum}`, 60, 180);


        // ctx.drawImage(this.boxBg, 107, 250, 82, 82);

        //头像
        const avatarX = 19;
        const avatarY = 205;
        const avatarW = 82;
        const avatarH = 82;
        this.drawAvatar(ctx, one.avatarUrl, avatarX, avatarY, avatarW, avatarH, (avatarImg) => {
            // if (prevOffsetY == this.offsetY) {
            ctx.drawImage(avatarImg, avatarX, avatarY, avatarW, avatarH);
            // }
        })

        //昵称
        const nick = one.nickname.length <= 6 ? one.nickname : one.nickname.substr(0, 5) + "...";

        if (isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "bold 26px Helvetic";
        ctx.fillText(`${nick}`, 60, 335);


        //分数
        if (isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "bold 30px Helvetica";
        ctx.fillText(`${one.KVDataList[0].value}`, 60, 385);

        // console.log('this.gameDatas', this.gameDatas)

        if (!two) {
            return;
        }

        //名次
        if (!isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "30px Helvetica";
        ctx.fillText(`${twoNum}`, 260, 180);


        //头像
        const avatarX1 = 219;
        const avatarY1 = 205;
        const avatarW1 = 82;
        const avatarH1 = 82;
        this.drawAvatar(ctx, two.avatarUrl, avatarX1, avatarY1, avatarW1, avatarH1, (avatarImg) => {
            // if (prevOffsetY == this.offsetY) {
            ctx.drawImage(avatarImg, avatarX1, avatarY1, avatarW1, avatarH1);
            // }
        })

        //昵称
        const nick1 = two.nickname.length <= 6 ? two.nickname : two.nickname.substr(0, 5) + "...";

        if (!isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "bold 26px Helvetic";
        ctx.fillText(`${nick1}`, 260, 335);

        //分数
        if (!isone) {
            ctx.fillStyle = '#00FC41'
        } else {
            ctx.fillStyle = '#ffffff'
        }
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "30px Helvetica";
        ctx.fillText(`${two.KVDataList[0].value}`, 260, 385);

        if (!three) {
            return;
        }



        //名次
        ctx.fillStyle = '#FFFFFF'
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "30px Helvetica";
        ctx.fillText(`${threeNum}`, 460, 180);


        //头像
        const avatarX2 = 419;
        const avatarY2 = 205;
        const avatarW2 = 82;
        const avatarH2 = 82;
        this.drawAvatar(ctx, three.avatarUrl, avatarX2, avatarY2, avatarW2, avatarH2, (avatarImg) => {
            // if (prevOffsetY == this.offsetY) {
            ctx.drawImage(avatarImg, avatarX2, avatarY2, avatarW2, avatarH2);
            // }
        })

        //昵称
        const nick2 = three.nickname.length <= 6 ? three.nickname : three.nickname.substr(0, 5) + "...";

        ctx.fillStyle = '#FFFFFF'
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "bold 26px Helvetic";
        ctx.fillText(`${nick2}`, 460, 335);

        //分数
        ctx.fillStyle = '#ffffff'
        ctx.textAlign = "center";
        ctx.baseLine = "middle";
        ctx.font = "30px Helvetica";
        ctx.fillText(`${three.KVDataList[0].value}`, 460, 385);

    }

    /**
     * 
     * @param {CanvasContext} ctx canvas上下文
     * @param {number} x 圆角矩形选区的左上角 x坐标
     * @param {number} y 圆角矩形选区的左上角 y坐标
     * @param {number} w 圆角矩形选区的宽度
     * @param {number} h 圆角矩形选区的高度
     * @param {number} r 圆角的半径
     */
    roundRect(ctx, x, y, w, h, r, img) {
        // 开始绘制
        ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        // ctx.setFillStyle('transparent')
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

        // border-top
        ctx.moveTo(x + r, y)
        ctx.lineTo(x + w - r, y)
        ctx.lineTo(x + w, y + r)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

        // border-right
        ctx.lineTo(x + w, y + h - r)
        ctx.lineTo(x + w - r, y + h)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

        // border-bottom
        ctx.lineTo(x + r, y + h)
        ctx.lineTo(x, y + h - r)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

        // border-left
        ctx.lineTo(x, y + r)
        ctx.lineTo(x + r, y)

        // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
        ctx.fill()
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, x, y, w, h) //将图片绘制进圆    
        ctx.restore();
    }

    moreThenFriend(score) {
        //let preScore = 0;
        let index = -1;
        for (let i = this.gameDatas.length - 1; i >= 0; i--) {
            let kvData = this.gameDatas[i].KVDataList[0];
            let grade = kvData ? kvData.value : 0;
            if (score < grade) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            index = 0;
        }

        // //头像
        // const avatarX = 50;
        // const avatarY = 320;
        // const avatarW = 60;
        // const avatarH = 60;
        // let ctx = this.sharedCtx;
        // this.drawAvatar(ctx, this.gameDatas[index].avatarUrl, avatarX, avatarY, avatarW, avatarH, (avatarImg) => {
        //     ctx.drawImage(avatarImg, avatarX, avatarY, avatarW, avatarH);

        // })

        //头像
        let avatarX = 0;
        let avatarY = 0;
        let radius = 100;
        let dy = 0;
        let ctx = this.sharedCtx;
        //const avatarH = 60;
        this.drawAvatar(ctx, this.gameDatas[index].avatarUrl, avatarX, avatarY, radius * 2, radius * 2, (avatarImg) => {
            // this.roundRect(ctx, 0, 0, 78, 78, 20, avatarImg);   
            ctx.drawImage(avatarImg, 0, 0, 78, 78)
        })
        this.cur_index = index;
    }

}

const rankList = new RankListRenderer();
rankList.listen();